import lodash from "lodash";
// import { getConditionValBol } from '@/mixins/tagmixin'
export const branchMixin = {
  props: {
    formSetting: {
      type: Object,
      default: () => {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default: () => {
        return {};
      }
    },
    node: {
      type: Object,
      default: () => {
        return {};
      }
    },
    jsPlumb: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      branchForm: {
        name: "", // 节点名称
        branchList: []
      },
      uniqueObj: {},
      rules: {
        name: [{ required: true, message: "请输入节点名称", trigger: "blur" }]
      }
    };
  },
  watch: {
    visible(val) {
      if (val) {
        this.nodeInit()
      }
    }
  },
  methods: {
    /**
     * 表单修改，这里可以根据传入的node的ID进行业务信息获取
     * @param data
     * @param node
     */
    async nodeInit() {
      this.branchForm.branchList = [];
      const { name } = this.node;
      this.getBranchList();
      this.branchForm.name = name;
    },
    /**
     * 获取当前分支节点下的子分支节点
     */
    getBranchList() {
      const { type, id } = this.node;
      switch (type) {
        case "timer":
          this.uniqueObj = { date: "" };
          break;
        case "random":
          this.uniqueObj = { rate: 0 };
          break;
        case "tenant":
          this.uniqueObj = {
            user_groupCodes: ""}
          break;
      }
      const { nodeList } = this.data;
      const { branchList } = this.branchForm;
      const childIdArr = this.getChildId(id); // 当前节点下的所有子节点Id
      for (let i = 0; i < childIdArr.length; i++) {
        const childId = childIdArr[i];
        for (let j = 0; j < nodeList.length; j++) {
          const { id, type: childType } = nodeList[j];
          if (childId === id && `${type}Child` === childType) {
            branchList.push({
              ...lodash.cloneDeep(this.uniqueObj),
              ...nodeList[j]
            });
          }
        }
      }
    },
    deleteBranch(index) {
      this.branchForm.branchList.splice(index, 1);
    },
    addBranch() {
      const { type, left, top } = this.node;
      const { branchList } = this.branchForm;
      const childLeft = parseInt(left) + 160;
      const childTop = parseInt(top) + branchList.length * 80;
      const branchNode = {
        id: this.getUUID(),
        name: "",
        ico: `market-${type}-child`,
        type: `${type}Child`,
        top: `${childLeft}px`,
        left: `${childTop}px`,
        ...lodash.cloneDeep(this.uniqueObj)
      };
      branchList.push(branchNode);
    },
    // 获取当前分支及当前分支的子分支节点外的其他节点名称
    getCanvasNodeName() {
      const { nodeList } = this.data;
      const { id } = this.node;
      const nodeIdArr = [...this.getChildId(id), id];
      return nodeList
        .filter(ele => !nodeIdArr.includes(ele.id))
        .map(ele => ele["name"]);
    },
    validateForm() {
      const { type } = this.node
      this.branchForm.branchList = this.branchForm.branchList.filter(
        branch => branch.name
      );
      const { name } = this.branchForm;
      const canvasNodenameArr = this.getCanvasNodeName();
      const branchNameArr = this.branchForm.branchList.map(
        branch => branch.name
      );
      const branchList = this.branchForm.branchList;
      if (branchList.length < 2) {
        return { status: "error", message: "子节点数量不能少于两个" };
      }
      if (branchNameArr.includes(name)) {
        return { status: "error", message: "节点名称与子节点名称重复" };
      }
      if (branchNameArr.length !== new Set(branchNameArr).size) {
        return { status: "error", message: "子节点名称重复" };
      }
      if (canvasNodenameArr.includes(name)) {
        return { status: "error", message: "节点名称与画布节点重复" };
      }
      // 群组节点由于排重节点原因，不判读子节点面层与画布节点重复
      for (let i = 0; i < branchNameArr.length; i++) {
        const name = branchNameArr[i];
        if (canvasNodenameArr.includes(name)&& type !== 'tenant') {
          return { status: "error", message: "子节点名称与画布节点重复" };
        }
      }
      return { status: "ok", message: "ok" };
    },
    setFormSetting() {
      const { type } = this.node;
      const branchList = this.branchForm.branchList;
      switch (type) {
        case "timer":
          branchList.forEach(({ id, date }) => {
            this.$set(this.formSetting, id, { date });
          });
          break;
          case "tenant" :
            branchList.forEach(({ id, user_groupCodes }) => {
              this.$set(this.formSetting, id, { user_groupCodes })
            })
            break
        case "random":
          branchList.forEach(({ id, rate }) => {
            this.$set(this.formSetting, id, { rate });
          });
          break;
      }
    },
    /**
     * 初始化分支子节点的坐标
     */
    initNodePlace(branchList) {
      const { left, top } = this.node;
      branchList.forEach((branch, index) => {
        const childLeft = parseInt(left) + branchList.length * 60;
        const childTop = parseInt(top) + index * 80;
        branch.left = `${childLeft}px`;
        branch.top = `${childTop}px`;
      });
    },
    /**
     * step0:初始化分支子节点的坐标
     * step1:删除当前分支节点下的子分支节点
     * step2:把当前的子分支节点添加到当前分支节点下
     */
    async save() {
      this.$refs.branchForm.validate(async valid => {
        if (valid) {
          const { status, message } = this.validateForm();
          if (status === "error") {
            return this.$message.error(message);
          }
          const branchList = this.branchForm.branchList;

          // 设置formSetting
          this.setFormSetting();

          /**
           * step0:对节点进行替换,新增，删除,初始化对应属性。
           * @param brancChildIdArr 当前画布选中的分支节点的子分支节点ID集合 如：[2,3,4]
           * @param nowBranchChildIdArr 当前分支弹框进行新增删除系列操作后的当前分支节点ID集合 如:[2,4,5,6,7]
           * @param deleteNodeIdArr // 原有画布需要删除的子分支节点 [3]
           * @param replaceNodeIdArr // 原有画布需要进行数据替换的子分支节点 [2,4]
           * @param replaceBranchList // 需要进行替换的分支列表数据 【2，4】的id 列表数据
           * @param addBranchList // 需要进行新增的的分支列表数据 [5,6,7]的id 列表数据
           */
          const { id: parentId } = this.node;
          const { name } = this.branchForm;
          const brancChildIdArr = this.getChildId(parentId);
          const nowBranchChildIdArr = branchList.map(branch => branch.id);
          const deleteNodeIdArr = brancChildIdArr.filter(
            nodeChildId => !nowBranchChildIdArr.includes(nodeChildId)
          );
          const replaceNodeIdArr = brancChildIdArr.filter(nodeChildId =>
            nowBranchChildIdArr.includes(nodeChildId)
          );
          const replaceBranchList = branchList.filter(({ id }) =>
            replaceNodeIdArr.includes(id)
          );
          const addBranchList = branchList.filter(
            ({ id }) => !replaceNodeIdArr.includes(id)
          );
          /**
           * step1:初始化分支子节点的坐标
           */
          // this.initNodePlace(addBranchList)
          this.initNodePlace(branchList);
          /**
           * step2 删除分支节点及formSetting对应的配置
           */
          this.data.nodeList = this.data.nodeList.filter(
            ({ id }) => !deleteNodeIdArr.includes(id)
          );
          deleteNodeIdArr.forEach(childId => {
            this.jsPlumb.removeAllEndpoints(childId);
            this.$delete(this.formSetting, childId);
          });
          /**
           * step3 替换子分支节点数据,如子分支节点的name属性
           */
          const nodeList = this.data.nodeList;
          for (let i = 0; i < nodeList.length; i++) {
            for (let j = 0; j < replaceBranchList.length; j++) {
              if (nodeList[i].id === replaceBranchList[j].id) {
                nodeList[i] = replaceBranchList[j];
                // nodeList[i].name = replaceBranchList[j].name;
              }
            }
          }
          /**
           * step4 把新的子分支节点添加到当前分支节点下,进行连线
           */
          await this.$nextTick();
          this.data.nodeList = [...this.data.nodeList, ...addBranchList];
          await this.$nextTick();
          addBranchList.forEach(branch => {
            this.makeSourceTarget(branch);
            this.jsPlumb.connect(
              {
                source: parentId,
                target: branch.id
              },
              this.jsplumbConnectOptions
            );
          });
          /**
           * step5::修改节点名称并重绘当前画布
           * @param reloadcanvas 与 @param repaintEverything 区别
           * reloadcanvas适用于step1 参数为branchlist 即对当前所有子分支节点做位置处理，位置处理在step3
           * repaintEverything适用于step1 参数为addBranchlist 即只对新增加的子分支节点做位置处理,位置处理在step4
           * 总结:对已有画布节点，改变想x,y的位置，却未触动node.vue的changeNodeSite方法，需要调用reloadcanvas，
           * 若只是初始化新的子节点，repaintEverything即可
           */
          this.data.nodeList.filter(node => {
            if (node.id === parentId) {
              node.name = name;
              // this.$emit("repaintEverything");
              this.$emit("reloadCanvas");
              this.cancel()
            }
          });
        }
      });
    },
    cancel() {
      this.$emit('update:visible', false)
    }
  }
};
